#include "connection_widget.h"
#include "connection_factory.h"

const QString CConnectionWidget::sDefaultHostname = "127.0.0.1";
const QString CConnectionWidget::sDefaultPort = "8960";

CConnectionWidget::CConnectionWidget(QWidget* pParent) :
	QWidget(pParent),
	mLayout(this),
  mConnectButton("&Connect"),
  mDisconnectButton("&Disconnect"),
	mHostnameLabel("Host:"),
	mHostnameEdit(this),
	mPortLabel("Port:"),
	mPortEdit(this),
	mClientConnection(NULL)
{
	setupUiElements();
	setupActions();
}
CConnectionWidget::~CConnectionWidget()
{
	if (mClientConnection != NULL)
	{
		CConnectionFactory::destroyClientConnection(mClientConnection);
	}
}

void CConnectionWidget::setupUiElements()
{
	mHostnameEdit.setMinimumWidth(100);
	mPortEdit.setFixedWidth(50);
	mPortEdit.setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
	mLayout.setAlignment(Qt::AlignLeft);
	mLayout.addWidget(&mHostnameLabel);
	mLayout.addWidget(&mHostnameEdit);
	mLayout.addWidget(&mPortLabel);
	mLayout.addWidget(&mPortEdit);
	mLayout.addWidget(&mConnectButton);
	mLayout.addWidget(&mDisconnectButton);

	mDisconnectButton.setEnabled(false);
	mHostnameEdit.setText(sDefaultHostname);
	mHostnameEdit.selectAll();
	mPortEdit.setText(sDefaultPort);
}

void CConnectionWidget::setupActions()
{
	connect(&mConnectButton, SIGNAL(clicked()), this, SLOT(connectClicked()));
	connect(&mDisconnectButton, SIGNAL(clicked()), this, SLOT(disconnectClicked()));
}

void CConnectionWidget::connectClicked()
{
	bool lOK(false);
	quint16 lPort = mPortEdit.text().toInt(&lOK, 10);
	if (lOK && mHostnameEdit.text().length() > 0)
	{
		emit connectRequested(mHostnameEdit.text(), lPort);
		mConnectButton.setEnabled(false);
	}
	else
	{
		/* FIXME display error in status bar */
	}
}

void CConnectionWidget::startClicked()
{
	emit startRequested();
}

void CConnectionWidget::disconnectClicked()
{
	emit disconnectRequested();
	mConnectButton.setEnabled(true);
	mDisconnectButton.setEnabled(false);
}

void CConnectionWidget::clientConnected(QString& pHost, quint16& pPort)
{
	mConnectButton.setEnabled(false);
	mDisconnectButton.setEnabled(true);
}

void CConnectionWidget::clientDisconnected()
{
	mConnectButton.setEnabled(true);
	mDisconnectButton.setEnabled(false);
}

void CConnectionWidget::connectionError()
{
	clientDisconnected();
}

